package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bzkj.basicinfo.domain.ncc.NccBasicReducedUnit;
import com.bzkj.basicinfo.domain.ncc.NccBasicSkuInfo;
import com.bzkj.basicinfo.domain.ncc.dto.NccBasicSkuInfoDto;
import com.bzkj.basicinfo.domain.ncc.erp.NccSkuInfoBean;
import com.bzkj.basicinfo.mapper.NccBasicReducedUnitMapper;
import com.bzkj.basicinfo.mapper.NccBasicSkuInfoMapper;
import com.bzkj.basicinfo.mapper.WmsStoStockMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicSkuInfoService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @Author wangzhichao
 * @ClassName NccBasicSkuInfoServiceImpl
 * @Date 2024/12/09 14:05:37
 * @description NCC商品信息
 */
@Service("nccBasicSkuInfoServiceImpl")
public class NccBasicSkuInfoServiceImpl implements NccBasicSkuInfoService {
    private static final Logger log = LoggerFactory.getLogger(NccBasicSkuInfoServiceImpl.class);
    @Autowired
    private NccBasicSkuInfoMapper nccBasicSkuInfoMapper;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Autowired
    private NccBasicReducedUnitMapper nccBasicReducedUnitMapper;

    @Autowired
    private WmsStoStockMapper stoStockMapper;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    /**
     * 根据条件查询ncc商品信息
     *
     * @Author wangzhichao
     * @Date 2024/12/10 16:24:47
     * @Param dto
     */
    @Override
    public List<NccBasicSkuInfo> findNccBasicSkuInfoData(NccBasicSkuInfoDto dto) {
        return nccBasicSkuInfoMapper.findNccBasicSkuInfoData(dto);
    }

    /**
     * 根据pk_material修改ncc商品信息
     *
     * @Author wangzhichao
     * @Date 2024/12/11 13:19:44
     * @Param entity
     */
    @Transactional
    @Override
    public AjaxResult nccBasicSkuInfoUpdate(NccBasicSkuInfo entity) {
        NccBasicSkuInfo one = nccBasicSkuInfoMapper.getNccBasicSkuInfoOne(entity.getCode());
        if (Objects.isNull(one)) {
            int i = nccBasicSkuInfoMapper.nccBasicSkuInfoUpdate(entity);

            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败未找到指定数据");
        } else {
            if (one.getPk_material().equals(entity.getPk_material())) {
                int i = nccBasicSkuInfoMapper.nccBasicSkuInfoUpdate(entity);
                NccBasicReducedUnit unit = new NccBasicReducedUnit();
                unit.setMeasrate(entity.getMeasrate());
                unit.setpK_MATERIAL(entity.getPk_material());
                unit.setpK_MEASDOC(entity.getPk_measdoc());
                nccBasicReducedUnitMapper.nccBasicReducedUnitUpdate(unit);

                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.error("修改失败code重复");
            }
        }
    }

    /**
     * 新增ncc商品信息
     *
     * @Author wangzhichao
     * @Date 2024/12/11 13:32:08
     * @Param entity
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult nccBasicSkuInfoSave(NccBasicSkuInfo entity) {
        NccBasicSkuInfo one = nccBasicSkuInfoMapper.getNccBasicSkuInfoOne(entity.getCode());
        if (Objects.isNull(one)) {
            try {
                String userName = SecurityUtils.getLoginUser().getUser().getUserName();
                String pkMaterial = "WMS" + uniq.generateUniqueIdentifier();
                entity.setPk_material(pkMaterial);
                entity.setCreateTime(new Date());
                entity.setCreator(userName);
                entity.setModifier(userName);
                entity.setModifierTime(new Date());
                entity.setTsTime(new Date());
                entity.setPk_group("0001A1100000000021CH");
                entity.setPk_source(pkMaterial);
                // 创建商品信息
                int i = nccBasicSkuInfoMapper.nccBasicSkuInfoSave(entity);

                NccBasicReducedUnit unit = new NccBasicReducedUnit();
                unit.setTs(new Date());
                unit.setMeasrate(entity.getMeasrate());
                unit.setpK_MATERIAL(entity.getPk_material());
                unit.setpK_MEASDOC(entity.getPk_measdoc());

                //创建商品转换系数信息
                nccBasicReducedUnitMapper.nccBasicReducedUnitSave(unit);

//                // 创建动态表
//                if(entity.getCreateDynamics()) {
//                    nccBasicSkuInfoCreateTableXXXSku(pkMaterial);
//                }
                return AjaxResult.success("新增成功");
            } catch (Exception e) {
                log.error("操作失败：{}", e);
                return AjaxResult.error("新增商品信息失败");
            }

        } else {
            return AjaxResult.error("新增失败code重复");
        }
    }

    /**
     * 根据pkMaterial修改商品信息
     *
     * @Author wangzhichao
     * @Date 2024/12/11 14:17:12
     * @Param status
     * @Param pk_material
     */
    @Override
    public AjaxResult nccBasicSkuInfoEnableStatusUpdate(String status, String pkMaterial) {
        int i = nccBasicSkuInfoMapper.nccBasicSkuInfoEnableStatusUpdate(status, pkMaterial);
        return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败未找到指定数据");
    }

    @Override
    public List<String> findNccBasicSkuInfoNameList(String name) {
        return nccBasicSkuInfoMapper.findNccBasicSkuInfoNameList(name);
    }

    @Autowired
    private HttpClientUtils hcu;

    /**
     * 定时任务
     * 定时获取采购订单数据
     * 获取当天数据
     * @param  flag 是否登录调用（true：登录调用查询返回当天时间段，false：定时任务调用查询返回前一天时间段）
     * @return
     */
    @Override
    public void jobMethodExecute(Boolean flag) {
        try {
            HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

            // 查询当前数据
            HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 1, pkOrgCode);
            JSONObject jsonNode = JSON.parseObject(response.body());
            // 收集rep系统数据
            List<NccSkuInfoBean> list = jsonNode.getJSONArray("data").toJavaList(NccSkuInfoBean.class);
            if (!list.isEmpty()) {
                extracted(list);
            }
        } catch (HttpException e) {
            log.error("同步失败:{}", e);
        }
    }

    @Override
    public void jobExpMethodExecute() {
        log.info("==========================根据效期自动冻结定时任务执行开始================================================");
        stoStockMapper.autoFreezeTask("1");
        log.info("==========================根据效期自动冻结定时任务执行结束================================================");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list 需要插入或更新的数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<NccSkuInfoBean> list) {
        for (NccSkuInfoBean nccSkuInfoBean : list) {
            nccBasicSkuInfoMapper.insertOrUpdate(nccSkuInfoBean);
        }
    }

    /**
     * 创建商品信息动态表
     *
     * @param tableName
     * @return
     */
    @Override
    public AjaxResult nccBasicSkuInfoCreateTableXXXSku(String tableName) {
        try {
            nccBasicSkuInfoMapper.nccBasicSkuInfoCreateTableXXXSku("table_" + tableName + "_sku");
            return AjaxResult.success("创建成功");
        } catch (Exception e) {
            log.error("创建失败：{}", e);
            return AjaxResult.error("创建失败");
        }
    }
}
